package com.ji.li.reactadminproexampleservice.filter;

import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(1)
@WebFilter(
        urlPatterns = {"/*"},
        filterName = "DataFilter"
)
public class DataFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(
            ServletRequest servletRequest,
            ServletResponse servletResponse,
            FilterChain filterChain
    ) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        /**
         * 设置允许跨域的配置
         * 这里填写你允许进行跨域的主机ip（正式上线时可以动态配置具体允许的域名和IP）
         */
        String curOrigin = req.getHeader("Origin");
//        res.setHeader("Access-Control-Allow-Origin", curOrigin ?: "true");
        res.setHeader("Access-Control-Allow-Origin", "*");
        /**
         *  允许的访问方法
         */
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        /**
         * Access-Control-Max-Age 用于 CORS 相关配置的缓存
         */
        res.setHeader("Access-Control-Max-Age", "3600");
        res.setHeader("Access-Control-Allow-Credentials", "true");
        /**
         * 头部信息
         */
        res.setHeader("Access-Control-Allow-Headers", "token,Origin, X-Requested-With, Content-Type, Accept");
        res.setHeader("Cache-Control", "no-cache");
        /**
         * 字符编码
         */
        servletResponse.setCharacterEncoding("UTF-8");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
